import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14

Item {
    id: userManagementPage
    
    property var qmlBridge
    
    property var userSess
    property var permMgr
    property var auditLog
    
    Rectangle {
        anchors.fill: parent
        color: "#f5f5f5"
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            // Header
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 60
                color: "#607D8B"
                radius: 8
                
                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 20
                    
                    Text {
                        text: "User Management"
                        font.pixelSize: 20
                        font.bold: true
                        color: "white"
                    }
                    
                    Item { Layout.fillWidth: true }
                    
                    Text {
                        text: "Current User: " + (userSess ? userSess.currentUser : "Unknown")
                        font.pixelSize: 14
                        color: "white"
                    }
                    
                    Button {
                        text: "Add User"
                        enabled: userSess ? userSess.hasPermission("user_management") : false
                        onClicked: addUserDialog.open()
                    }
                }
            }
            
            // User Statistics
            RowLayout {
                Layout.fillWidth: true
                spacing: 20
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 5
                        
                        Text {
                            text: userListModel.count.toString()
                            font.pixelSize: 24
                            font.bold: true
                            color: "#2196F3"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            text: "Total Users"
                            font.pixelSize: 14
                            color: "#666"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    function getActiveUsersCount() {
                        var count = 0
                        for (var i = 0; i < userListModel.count; i++) {
                            if (userListModel.get(i).isActive) count++
                        }
                        return count
                    }
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 5
                        
                        Text {
                            text: parent.parent.getActiveUsersCount().toString()
                            font.pixelSize: 24
                            font.bold: true
                            color: "#4CAF50"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            text: "Active Users"
                            font.pixelSize: 14
                            color: "#666"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: "white"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 5
                        
                        Text {
                            text: "1"
                            font.pixelSize: 24
                            font.bold: true
                            color: "#FF9800"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            text: "Online Now"
                            font.pixelSize: 14
                            color: "#666"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }
                }
            }
            
            // User List
            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: "white"
                radius: 8
                border.color: "#e0e0e0"
                border.width: 1
                
                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 20
                    spacing: 15
                    
                    RowLayout {
                        Layout.fillWidth: true
                        
                        Text {
                            text: "User Accounts"
                            font.pixelSize: 18
                            font.bold: true
                            color: "#333"
                        }
                        
                        Item { Layout.fillWidth: true }
                        
                        TextField {
                            id: searchField
                            placeholderText: "Search users..."
                            onTextChanged: filterUsers()
                        }
                    }
                    
                    // Table Header
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 40
                        color: "#f5f5f5"
                        border.color: "#e0e0e0"
                        border.width: 1
                        
                        RowLayout {
                            anchors.fill: parent
                            anchors.margins: 10
                            spacing: 10
                            
                            Text {
                                Layout.preferredWidth: 150
                                text: "Username"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 100
                                text: "Role"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 80
                                text: "Status"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 150
                                text: "Last Login"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.preferredWidth: 100
                                text: "Failed Attempts"
                                font.bold: true
                                color: "#333"
                            }
                            
                            Text {
                                Layout.fillWidth: true
                                text: "Actions"
                                font.bold: true
                                color: "#333"
                            }
                        }
                    }
                    
                    // User List
                    ListView {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        model: userListModel
                        delegate: userDelegate
                        
                        ScrollBar.vertical: ScrollBar {}
                    }
                }
            }
        }
    }
    
    // User List Model
    ListModel {
        id: userListModel
        
        Component.onCompleted: {
            loadUserData()
        }
    }
    
    // User Delegate
    Component {
        id: userDelegate
        
        Rectangle {
            width: ListView.view.width
            height: 60
            color: index % 2 === 0 ? "#f9f9f9" : "white"
            border.color: "#e0e0e0"
            border.width: 1
            
            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 10
                
                Text {
                    Layout.preferredWidth: 150
                    text: username
                    font.pixelSize: 14
                    color: "#333"
                    font.bold: username === (userSess ? userSess.currentUser : "")
                }
                
                Rectangle {
                    Layout.preferredWidth: 100
                    height: 25
                    color: getRoleColor(role)
                    radius: 12
                    
                    Text {
                        anchors.centerIn: parent
                        text: role
                        color: "white"
                        font.pixelSize: 10
                        font.bold: true
                    }
                    
                    function getRoleColor(role) {
                        switch(role) {
                            case "administrator": return "#9C27B0"
                            case "operator": return "#2196F3"
                            case "viewer": return "#607D8B"
                            default: return "#9E9E9E"
                        }
                    }
                }
                
                Rectangle {
                    Layout.preferredWidth: 80
                    height: 25
                    color: isActive ? "#4CAF50" : "#F44336"
                    radius: 12
                    
                    Text {
                        anchors.centerIn: parent
                        text: isActive ? "Active" : "Inactive"
                        color: "white"
                        font.pixelSize: 10
                        font.bold: true
                    }
                }
                
                Text {
                    Layout.preferredWidth: 150
                    text: lastLogin || "Never"
                    font.pixelSize: 12
                    color: "#666"
                }
                
                Text {
                    Layout.preferredWidth: 100
                    text: failedAttempts.toString()
                    font.pixelSize: 12
                    color: failedAttempts > 0 ? "#F44336" : "#666"
                    horizontalAlignment: Text.AlignHCenter
                }
                
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 5
                    
                    Button {
                        text: "Edit"
                        enabled: userSess ? userSess.hasPermission("user_management") : false
                        onClicked: editUser(index)
                    }
                    
                    Button {
                        text: isActive ? "Disable" : "Enable"
                        enabled: userSess ? userSess.hasPermission("user_management") : false
                        onClicked: toggleUserStatus(index)
                    }
                    
                    Button {
                        text: "Reset Password"
                        enabled: userSess ? userSess.hasPermission("user_management") : false
                        onClicked: resetUserPassword(index)
                    }
                }
            }
        }
    }
    
    // Add User Dialog
    Dialog {
        id: addUserDialog
        title: "Add New User"
        width: 400
        height: 350
        anchors.centerIn: parent
        modal: true
        
        ColumnLayout {
            anchors.fill: parent
            spacing: 15
            
            TextField {
                id: newUsernameField
                Layout.fillWidth: true
                placeholderText: "Username"
            }
            
            TextField {
                id: newPasswordField
                Layout.fillWidth: true
                placeholderText: "Password"
                echoMode: TextInput.Password
            }
            
            TextField {
                id: confirmPasswordField
                Layout.fillWidth: true
                placeholderText: "Confirm Password"
                echoMode: TextInput.Password
            }
            
            ComboBox {
                id: newUserRoleCombo
                Layout.fillWidth: true
                model: ["operator", "administrator", "viewer"]
                currentIndex: 0
            }
            
            CheckBox {
                id: newUserActiveCheck
                text: "Account Active"
                checked: true
            }
            
            Item { Layout.fillHeight: true }
            
            RowLayout {
                Layout.fillWidth: true
                
                Button {
                    text: "Cancel"
                    onClicked: {
                        clearAddUserDialog()
                        addUserDialog.close()
                    }
                }
                
                Item { Layout.fillWidth: true }
                
                Button {
                    text: "Create User"
                    enabled: newUsernameField.text.length > 0 && 
                            newPasswordField.text.length > 0 && 
                            newPasswordField.text === confirmPasswordField.text
                    onClicked: {
                        createNewUser()
                        clearAddUserDialog()
                        addUserDialog.close()
                    }
                }
            }
        }
    }
    
    // Edit User Dialog
    Dialog {
        id: editUserDialog
        title: "Edit User"
        width: 400
        height: 300
        anchors.centerIn: parent
        modal: true
        
        property int editIndex: -1
        
        ColumnLayout {
            anchors.fill: parent
            spacing: 15
            
            TextField {
                id: editUsernameField
                Layout.fillWidth: true
                placeholderText: "Username"
                enabled: false // Username cannot be changed
            }
            
            ComboBox {
                id: editUserRoleCombo
                Layout.fillWidth: true
                model: ["operator", "administrator", "viewer"]
            }
            
            CheckBox {
                id: editUserActiveCheck
                text: "Account Active"
            }
            
            Text {
                text: "Failed Login Attempts: " + (editUserDialog.editIndex >= 0 ? userListModel.get(editUserDialog.editIndex).failedAttempts : 0)
                color: "#666"
            }
            
            Button {
                Layout.fillWidth: true
                text: "Reset Failed Attempts"
                onClicked: resetFailedAttempts()
            }
            
            Item { Layout.fillHeight: true }
            
            RowLayout {
                Layout.fillWidth: true
                
                Button {
                    text: "Cancel"
                    onClicked: editUserDialog.close()
                }
                
                Item { Layout.fillWidth: true }
                
                Button {
                    text: "Save Changes"
                    onClicked: {
                        saveUserChanges()
                        editUserDialog.close()
                    }
                }
            }
        }
    }
    
    // Functions
    function loadUserData() {
        userListModel.clear()
        
        // Sample user data - in real implementation, this would come from database
        var sampleUsers = [
            {
                username: "admin",
                role: "administrator",
                isActive: true,
                lastLogin: "2024-01-15 10:30:15",
                failedAttempts: 0
            },
            {
                username: "operator",
                role: "operator",
                isActive: true,
                lastLogin: "2024-01-14 16:45:22",
                failedAttempts: 0
            },
            {
                username: "viewer1",
                role: "viewer",
                isActive: true,
                lastLogin: "2024-01-13 09:15:30",
                failedAttempts: 1
            },
            {
                username: "test_user",
                role: "operator",
                isActive: false,
                lastLogin: "",
                failedAttempts: 3
            }
        ]
        
        for (var i = 0; i < sampleUsers.length; i++) {
            userListModel.append(sampleUsers[i])
        }
    }
    
    function filterUsers() {
        console.log("Filtering users:", searchField.text)
        // In real implementation, this would filter the user list
    }
    
    function editUser(index) {
        var user = userListModel.get(index)
        editUserDialog.editIndex = index
        editUsernameField.text = user.username
        editUserRoleCombo.currentIndex = editUserRoleCombo.find(user.role)
        editUserActiveCheck.checked = user.isActive
        editUserDialog.open()
    }
    
    function toggleUserStatus(index) {
        var user = userListModel.get(index)
        userListModel.setProperty(index, "isActive", !user.isActive)
        
        // Log audit event
        if (auditLog) {
            console.log("User status changed:", user.username, user.isActive ? "activated" : "deactivated")
        }
    }
    
    function resetUserPassword(index) {
        var user = userListModel.get(index)
        console.log("Reset password for user:", user.username)
        // In real implementation, this would reset the user's password
    }
    
    function createNewUser() {
        var newUser = {
            username: newUsernameField.text,
            role: newUserRoleCombo.currentText,
            isActive: newUserActiveCheck.checked,
            lastLogin: "",
            failedAttempts: 0
        }
        
        userListModel.append(newUser)
        
        // Log audit event
        if (auditLog) {
            console.log("New user created:", newUser.username, newUser.role)
        }
    }
    
    function saveUserChanges() {
        if (editUserDialog.editIndex >= 0) {
            userListModel.setProperty(editUserDialog.editIndex, "role", editUserRoleCombo.currentText)
            userListModel.setProperty(editUserDialog.editIndex, "isActive", editUserActiveCheck.checked)
            
            // Log audit event
            if (auditLog) {
                var user = userListModel.get(editUserDialog.editIndex)
                console.log("User updated:", user.username)
            }
        }
    }
    
    function resetFailedAttempts() {
        if (editUserDialog.editIndex >= 0) {
            userListModel.setProperty(editUserDialog.editIndex, "failedAttempts", 0)
        }
    }
    
    function clearAddUserDialog() {
        newUsernameField.text = ""
        newPasswordField.text = ""
        confirmPasswordField.text = ""
        newUserRoleCombo.currentIndex = 0
        newUserActiveCheck.checked = true
    }
}